"""
示例：动作自动分类和评估

演示方案1的完整流程：
1. 专家视频：长视频包含多个动作 → 手动标注分割 → 建立多个模板
2. 患者视频：长视频包含多个动作 → 自动分割 → 自动分类 → 自动评分
"""

import os
import yaml
import logging

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)

print("=" * 60)
print("康复评估系统 - 自动分类示例")
print("=" * 60)
print()


def example_build_from_segments():
    """
    示例：从长视频的分段建立多个模板

    适用场景：专家录制了一个长视频，包含多个不同动作（蹲下、抬腿等）
    """
    print("示例 1: 从专家长视频建立多动作模板")
    print("-" * 60)

    from src.utils.template_builder import TemplateBuilder

    # Load configuration
    with open('config.yaml', 'r') as f:
        config = yaml.safe_load(f)

    # Initialize template builder
    builder = TemplateBuilder(
        templates_dir=config['paths']['templates'],
        config=config
    )

    # 专家长视频路径（包含多个动作）
    expert_video_path = './templates/squat/down.mp4'  # 临时使用已有视频

    if not os.path.exists(expert_video_path):
        print(f"⚠️  请先准备专家演示视频: {expert_video_path}")
        print("   跳过此示例...")
        print()
        return

    print(f"正在处理专家视频: {expert_video_path}")
    print()
    print("说明: 系统会自动分割视频，然后您需要标注每个分段的动作类型")
    print()

    # 手动标注分段（实际应用中可以通过UI或配置文件）
    # 格式：{segment_id: 'action_type'}
    segments_labels = {
        0: 'squat',      # 第一个检测到的段是蹲下
        1: 'squat'       # 第二个检测到的段也是蹲下
        # 如果视频包含抬腿，可以添加：1: 'leg_raise'
    }

    print(f"手动标注: {segments_labels}")
    print()

    # 从分段建立模板
    templates = builder.build_templates_from_segments(
        video_path=expert_video_path,
        segments_labels=segments_labels,
        template_name='expert',
        metadata={'description': '专家示范多动作视频'}
    )

    print()
    print(f"✓ 成功建立 {len(templates)} 个模板:")
    for name, paths in templates.items():
        print(f"  - {name}: {paths['meta_path']}")
    print()


def example_auto_classify_and_score():
    """
    示例：患者视频自动分类和评分

    适用场景：患者录制长视频，系统自动分割、识别动作类型、匹配模板评分
    """
    print("示例 2: 患者视频自动分类和评分")
    print("-" * 60)

    from src.core.pose_detector import PoseDetector
    from src.core.skeleton_normalizer import SkeletonNormalizer
    from src.core.feature_extractor import FeatureExtractor
    from src.core.action_segmenter import ActionSegmenter
    from src.core.action_classifier import ActionClassifier
    from src.core.matcher import ActionMatcher
    from src.core.report_generator import ReportGenerator
    from src.utils.template_builder import TemplateBuilder

    # Load configuration
    with open('config.yaml', 'r') as f:
        config = yaml.safe_load(f)

    # 患者视频路径（包含多个动作）
    patient_video_path = './templates/squat/down.mp4'  # 临时使用专家视频测试

    if not os.path.exists(patient_video_path):
        print(f"⚠️  请先准备患者视频: {patient_video_path}")
        print("   跳过此示例...")
        print()
        return

    print(f"正在评估患者视频: {patient_video_path}")
    print("(注意: 临时使用专家视频作为患者视频进行测试)")
    print()

    # Initialize components
    print("1. 初始化组件...")
    pose_detector = PoseDetector(
        model_complexity=config['pose_detection']['model_complexity']
    )
    skeleton_normalizer = SkeletonNormalizer(
        canvas_size=tuple(config['skeleton']['canvas_size'])
    )
    feature_extractor = FeatureExtractor(
        device=config['feature_extraction']['device']
    )
    action_segmenter = ActionSegmenter(
        window_size=config['segmentation']['window_size'],
        threshold_multiplier=config['segmentation']['threshold_multiplier'],
        min_action_length=config['segmentation']['min_action_length'],
        max_action_length=config['segmentation']['max_action_length']
    )
    action_classifier = ActionClassifier(confidence_threshold=0.3)
    action_matcher = ActionMatcher()
    report_generator = ReportGenerator()
    template_builder = TemplateBuilder(config=config)

    # Process patient video
    print("2. 检测姿态...")
    landmarks_seq, metadata = pose_detector.detect_from_video(patient_video_path)
    landmarks_seq = pose_detector.interpolate_missing_frames(landmarks_seq)

    print("3. 归一化和渲染骨架...")
    normalized_seq, rendered_imgs = skeleton_normalizer.process_sequence(landmarks_seq)

    print("4. 提取深度特征...")
    patient_features = feature_extractor.extract_from_sequence(rendered_imgs)

    print("5. 切分动作并检测阶段...")
    segments_with_phases = action_segmenter.segment_with_phases(
        normalized_seq,
        fps=metadata.get('fps', 30.0),
        action_type='default'
    )
    print(f"   检测到 {len(segments_with_phases)} 个动作段")

    # Load all available templates
    print("6. 加载所有可用模板...")
    all_templates = template_builder.load_all_templates()
    print(f"   找到 {len(all_templates)} 个模板: {list(all_templates.keys())}")

    if len(all_templates) == 0:
        print("⚠️  没有可用模板，请先运行示例 1 建立模板")
        return

    print()
    print("7. 自动分类和评分...")

    results = []
    for i, segment_info in enumerate(segments_with_phases):
        start = segment_info['start']
        end = segment_info['end']
        patient_phases = segment_info['phases']

        # Extract segment features
        seg_features = patient_features[start:end]
        seg_landmarks = normalized_seq[start:end]

        # Classify action type
        action_type, confidence = action_classifier.classify_segment(
            seg_features,
            all_templates
        )

        print(f"\n   动作段 {i+1}: 帧{start}-{end}")
        print(f"     分类结果: {action_type} (置信度: {confidence:.3f})")

        if action_type == 'unknown':
            print(f"     ⚠️  无法识别动作类型，跳过评分")
            continue

        # Get corresponding template
        template = all_templates[action_type]

        # Add squat-specific phases to template
        if 'peak' in template.get('phases', {}):
            template_peak = template['phases']['peak']
            template_start = 0
            template_end = template['num_frames']
            template['phases']['squat_down'] = (template_start, template_peak)
            template['phases']['squat_up'] = (template_peak, template_end)

        # Overall segment score
        overall_score = action_matcher.compute_comprehensive_score(
            seg_features,
            template['features'],
            seg_landmarks,
            template['landmarks']
        )

        # Phase-specific scores
        phase_scores = {}
        if template.get('phases'):
            phase_scores = action_matcher.compute_phase_scores(
                patient_features,
                template['features'],
                normalized_seq,
                template['landmarks'],
                patient_phases,
                template['phases']
            )

        # Combine results
        result = {
            'action_type': action_type,
            'classification_confidence': confidence,
            'frame_range': [int(start), int(end)],
            **overall_score,
            'phase_scores': phase_scores,
            'phases': patient_phases
        }
        results.append(result)

        print(f"     整体得分: {overall_score['final_score']:.2f}")
        if phase_scores.get('squat_down'):
            print(f"     下蹲阶段得分: {phase_scores['squat_down']['final_score']:.2f}")
        if phase_scores.get('squat_up'):
            print(f"     起立阶段得分: {phase_scores['squat_up']['final_score']:.2f}")

    # Generate report
    print("\n8. 生成评估报告...")
    session_id = 'auto_classify_session'
    report_paths = report_generator.generate_full_report(
        session_id,
        results,
        metadata={'video_path': patient_video_path}
    )

    print()
    print("✓ 评估完成!")
    if len(results) > 0:
        avg_score = sum(r['final_score'] for r in results) / len(results)
        print(f"  - 总体评分: {avg_score:.2f}")
        print(f"  - 动作段数: {len(results)}")

        # 统计动作类型
        action_counts = {}
        for r in results:
            action_type = r['action_type']
            action_counts[action_type] = action_counts.get(action_type, 0) + 1
        print(f"  - 动作统计: {action_counts}")
    else:
        print(f"  - 总体评分: N/A (未检测到动作段)")

    print(f"  - JSON 报告: {report_paths.get('json', 'N/A')}")
    print(f"  - HTML 报告: {report_paths.get('html', 'N/A')}")
    print()


def main():
    """Run examples."""

    # Example 1: Build templates from segmented expert video
    # example_build_from_segments()

    # Example 2: Auto-classify and score patient video
    example_auto_classify_and_score()

    print("=" * 60)
    print("说明:")
    print("  - 示例 1 展示如何从专家长视频建立多个动作模板")
    print("  - 示例 2 展示患者视频的自动分类和评分流程")
    print("  - 当前使用专家视频测试，实际应用中可使用不同的患者视频")
    print("=" * 60)


if __name__ == '__main__':
    main()
